#include <Eigen/Dense>
#include <iostream>
#include <vector>

int test_main4() 
{
    using namespace Eigen;

    std::vector<double> x_data = { 1, 2, 3, 4, 5 };
    std::vector<double> y_data = { 2.2, 2.8, 3.6, 4.5, 5.1 };

    const int N = x_data.size();
    MatrixXd A(N, 2);
    VectorXd b(N);

    for (int i = 0; i < N; ++i) {
        A(i, 0) = x_data[i];
        A(i, 1) = 1.0;       // 常数项
        b(i) = y_data[i];
    }

    // 求解最小二乘（推荐 QR）
    Vector2d result = A.colPivHouseholderQr().solve(b);
    std::cout << "拟合直线: y = " << result(0) << " * x + " << result(1) << std::endl;

    return 0;
}
